import type { Context, Next } from 'koa'

import { deSign } from '../util'

// token 校验
export const Authorize = () => {
  return (context: unknown, key: string) => {
    context[key].authorize = async (ctx: Context, next: Next) => {
      try {
        const token: string = ctx.headers.authorization || ''
        if (token) {
          // ctx.state.user = deSign(token.replace(/Bearer /, ''))
          const user = deSign(token.replace(/Bearer /, ''))
          if (user.time && user.time > Date.now()) {
            ctx.state.user = user
            return await next()
          }
          return ctx.throw(401, '登录过期-token 失效')
        }
        return ctx.throw(401, '当前未登录')
      } catch (error) {
        return ctx.throw(401, '登录过期-' + error)
      }
    }
  }
}
